package cn.com.sbell.vss.csg.vap;

import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import cn.com.sbell.vss.ICommander;
import cn.com.sbell.vss.Response;
import cn.com.sbell.vss.VssConstants;
import cn.com.sbell.vss.csg.vap.bean.VideoSignal;
import cn.com.sbell.vss.csg.vap.bean.VideoState;

import cn.com.sbell.vss.csg.vsclient.util.BeanValidator;
import cn.com.sbell.vss.csg.vsclient.util.PropertiesHolder;
import cn.com.sbell.vss.util.VideoSignalDispatchGroup;

public class ReportVideoSignalState implements ICommander {
	// private VideoSignalDispatchGroup videoDispatch;

	public Response execute(HttpServletRequest request) {
		Response response = Response.createResponse(request);
		// PropertiesHolder holder = PropertiesHolder
		// .getInstanceFromRequest(request);
		VideoSignal videoSignal = new VideoSignal();
		videoSignal.setDeviceId(request.getParameter("deviceId"));
		videoSignal.setTimestamp(request.getParameter("timestamp"));
		BeanValidator.validateNotNull(videoSignal, new String[] { "deviceId" });
		if (videoSignal.getTimestamp() == null
				|| videoSignal.getTimestamp().trim().length() == 0) {
			long time = System.currentTimeMillis();
			SimpleDateFormat format = new SimpleDateFormat(
					VssConstants.PATTERN_TIMESTAMP);
			videoSignal.setTimestamp(format.format(new Date(time)));
		}
		VideoState[] states = parseVideoState(request);
		videoSignal.setVideoState(states);

		VideoSignalDispatchGroup.getSignalDispatchGroup().addVideoSignal(
				videoSignal);
		response.setReturnCode(VssConstants.CODE_SUCCESS);
		return response;
	}

	// public void setVideoDispatch(VideoSignalDispatchGroup videoDispatch) {
	// this.videoDispatch = videoDispatch;
	// }

	private VideoState[] parseVideoState(HttpServletRequest request) {
		String[] videoStateString = request.getParameterValues("videoState");
		if (videoStateString == null) {
			return new VideoState[0];
		}
		VideoState[] state = new VideoState[videoStateString.length];
		for (int i = 0; i < videoStateString.length; i++) {
			String[] sta = videoStateString[i].split(",");
			state[i]=new VideoState();			
			state[i].setVideoId(new Integer(sta[0]));
			state[i].setVideoState(sta[1]);
		}
		return state;
	}

}
